package com.heba.greenmulu.message;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.notice.ItemReviewNoticeObject;
import com.heba.config.CommonConfig;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.businesslist.BusinessHomePageActivity;
import com.heba.greenmulu.businesslist.BusinessPersonActivity;
import com.heba.greenmulu.diary.ItemDiaryCommentActivity;
import com.heba.greenmulu.diary.ItemPersonHomePageActivity;
import com.heba.greenmulu.user.UserDiaryListActivity;
import com.heba.helper.DateHelper;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.CommonUtils;
import com.heba.utils.GlideUtil;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 評論通知列表
 * Created by jason on 2020/1/14.
 */
public class ItemNotificationReviewActivity extends BaseActivity {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private List<ItemReviewNoticeObject> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_notification_recycler);
        initTopbar();
        findViewById();
        initView();
        getReviewNoticeData();
    }

    @Override
    protected void findViewById() {
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recyclerView);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.message_review));
        txt_right.setVisibility(View.INVISIBLE);
        txt_right.setText(getResources().getString(R.string.message_notification_clear));

        list = new ArrayList<>();

        recycleAdapter = new QuickAdapter<ItemReviewNoticeObject>(list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.recycle_item_notification_review;
            }

            @Override
            public void convert(VH holder, ItemReviewNoticeObject data, int position) {
                ImageView iv_avatar = holder.getView(R.id.iv_avatar);
                GlideUtil.loadImageWithPlaceHolderID(ItemNotificationReviewActivity.this, data.getIcon(), iv_avatar, R.drawable.icon_head_portrait);
                holder.setText(R.id.tv_name, data.getAccount());
                holder.setText(R.id.tv_time, DateHelper.transferDateString(ItemNotificationReviewActivity.this, data.getTimeCreated()));
                holder.getView(R.id.iv_photo).setVisibility(View.INVISIBLE);
                if (data.getImageUrl() != null && !data.getImageUrl().isEmpty()) {
                    holder.getView(R.id.iv_photo).setVisibility(View.VISIBLE);
                    GlideUtil.loadImageWithDefaultPlaceHolder(ItemNotificationReviewActivity.this, data.getImageUrl(), holder.getView(R.id.iv_photo));
                }

                TextView tv_content = holder.getView(R.id.tv_content);
                TextView tv_reply = holder.getView(R.id.tv_reply);
                /**
                 * 根據Type判斷是評論日誌還是回復評論
                 */
                switch (data.getType()) {
                    case 0:
                        //評論日誌
                        tv_content.setText(getResources().getString(R.string.message_diary_review));
                        tv_reply.setText(CommonUtils.getDecodeText(data.getMessage()));
                        break;
                    case 1:
                        //回復評論
                        tv_content.setText(String.format(getResources().getString(R.string.message_review_reply), CommonUtils.getDecodeText(data.getFeedbackMsg())));
                        tv_reply.setText(CommonUtils.getDecodeText(data.getMessage()));
                        break;
                    default:
                        break;
                }

                iv_avatar.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.SEND_USER_ID, data.getUserID());
                    if (data.getAccountType() == 0){
                        openActivity(ItemPersonHomePageActivity.class, bundle);
                    }else{
                        openActivity(BusinessPersonActivity.class, bundle);
                    }
                });

                /**
                 * 跳转日记详情页面
                 */
                holder.itemView.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putInt(CommonConfig.TYPE, 1);
                    bundle.putString(CommonConfig.DIARY_ID, String.valueOf(data.getDiaryID()));
                    openActivity(UserDiaryListActivity.class, bundle);
                });

                /**
                 * 跳转到所有留言页面
                 */
                tv_reply.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.DIARY_ID, String.valueOf(data.getDiaryID()));
                    openActivity(ItemDiaryCommentActivity.class, bundle);
                });
            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            Page = 1;
            isRefreshFromTop = true;
            getReviewNoticeData();
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Page++;
            isRefreshFromTop = false;
            getReviewNoticeData();
        });
    }

    /**
     * 獲取評論通知列表數據
     */
    private void getReviewNoticeData() {
        if (firstRefresh) {
            firstRefresh = false;
            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", PerPage);
        client.get(Cfg.BaseUrl + "/Notice/Reply", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);

                        /**
                         * 下拉刷新处理
                         */
                        if (isRefreshFromTop) {
                            isRefreshFromTop = false;
                            refreshLayout.setNoMoreData(false);
                            list.clear();
                        }

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemReviewNoticeObject> noticeObjects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemReviewNoticeObject>>() {
                                }.getType());
                                list.addAll(list.size(), noticeObjects);
                            } else {
                                //无数据
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //刷新数据
                        recycleAdapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);
                    }

                });
    }
}
